package ${webPackageName}.controller.sys;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import ${commonPackageName}.annotation.Permission;
import ${commonPackageName}.annotation.RequestLog;
import ${commonPackageName}.utils.ImageVerificationCode;
import ${commonPackageName}.utils.RedisUtil;
import ${servicePackageName}.dto.sys.LoginDto;
import ${servicePackageName}.qo.sys.LoginReq;
import ${servicePackageName}.service.sys.AuthSerivce;
import ${servicePackageName}.vo.other.ExportVo;
import ${webPackageName}.utils.RequestHolder;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.IdUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 登录校验
 * @author lleice
 *
 */
@Api(tags = {"登录相关接口"})
@RestController
@RequestMapping("/base/auth")
<#noparse>
public class SysAuthController {
    @Autowired
    private RedisUtil redisUtil;
	
	@Autowired
	private AuthSerivce authSerivce;

	@ApiOperation(value = "登录")
	@RequestLog
    @RequestMapping(value = "/login", method = RequestMethod.POST)
	public LoginDto login(@Validated @RequestBody LoginReq loginReq) throws Exception{
	 return authSerivce.login(loginReq);
 }
	
	
	@ApiOperation(value = "登出")
    @RequestMapping(value = "/logout", method = RequestMethod.POST)
	@Permission
	@RequestLog
	public Boolean logout() throws Exception{
		//从redis删除缓存
		redisUtil.del(RequestHolder.getCurrentUser().getToken());
		return true;
	}
	
	@ApiOperation(value = "获取图片验证码")
    @RequestMapping(value = "/code", method = RequestMethod.GET)
	public ExportVo orgInfoList(HttpServletRequest req, HttpServletResponse resp) throws Exception{
		//先删除原有的验证码
		String redisKey = "veirycode_"+IdUtil.fastSimpleUUID();
		// 写json到客户端
        ImageVerificationCode ivc = new ImageVerificationCode();
        BufferedImage image = ivc.getImage();
        System.out.println("验证码:"+ivc.getText());
        redisUtil.set(redisKey, ivc.getText(), 300L);
        try {
        	ByteArrayOutputStream stream = new ByteArrayOutputStream();
			ImageIO.write(image, "jpeg", stream);
			byte[] bytes = stream.toByteArray();
			String base64 = Base64.encode(bytes);
			return new ExportVo().setBase64Str(base64).setCaptchaKey(redisKey);
		} catch (IOException e) {
			e.printStackTrace();
		}
        return null;
	}
	
	
}
</#noparse>